﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BaBaoFan.Modifier.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace BaBaoFan.Modifier.Controllers
{
    public class AccountController : Controller
    {
        private readonly IUserInfoService userInfoService;
        private readonly IMemoryCache memoryCache;
        public AccountController(IUserInfoService userInfoService, IMemoryCache memoryCache)
        {
            this.userInfoService = userInfoService;
            this.memoryCache = memoryCache;
        }
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Login(string userName, string password)
        {

            var userInfo = userInfoService.Login(userName, password);
            if (userInfo != null)
            {
                var sessionId = Guid.NewGuid().ToString();
                this.HttpContext.Response.Cookies.Append("sessionId", sessionId);
                memoryCache.Set(sessionId, userInfo, new TimeSpan(24, 0, 0));
                return Json("ok");
            }
            else
            {
                return Json("no");
            }
        }

        public IActionResult LoginOut()
        {
            var sessionId = Request.Cookies["sessionId"] as string;//取出cookies里的key
            memoryCache.Remove(sessionId);
            this.HttpContext.Response.Cookies.Delete("sessionId");
            return Redirect(nameof(Login));
        }
    }
}